<!-- 动态管理 -->
<!-- 图片功能，用户名称未做-->
<template>
    <div class="container">
        <!-- 搜索跟创建 -->
        <div class="content-top">
            <el-input class="search-input" v-model="searchVal" :placeholder="toggleSearch ? '请输入ID' : '请输入标题'"></el-input>
            <!-- <el-tooltip :content="toggleSearch ? '切换为名称' : '切换为ID'" placement="bottom">
                <el-switch
                v-model="toggleSearch"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: rgb(19, 122, 206)"
                />
            </el-tooltip> -->
            <el-button v-if="toggleSearch" icon="Search" @click="searchById" round>搜索</el-button>
            <el-button v-else @click="searchByName" icon="Search" round>搜索</el-button>
            <el-button @click="loadContestNewsList" round>清除搜索</el-button>
            <!-- 创建按钮，round，圆角按钮 -->
            <el-button @click="createContest" type="primary" round>创建赛事动态</el-button>
            <div
                style="font-family: 微软雅黑;line-height:25px;margin-left: 472px;height:30px;font-size: 24px;border: 2px solid rgb(64, 158, 255);border-radius:5px;padding: 0px 20px; color: white;background-color: rgb(64, 158, 255);">
                动态管理</div>
        </div>

        <!-- 内容 -->
        <el-table :data="contestNewsList" border max-height="calc(100vh - 190px) ">
            <el-table-column label="序号" type="index" align="center" width="85"></el-table-column>
            <el-table-column label="标题" prop="title" align="center"></el-table-column>
            <el-table-column label="动态内容" prop="content" align="center"></el-table-column>
            <el-table-column label="发布者" prop="nickName" align="center" width="120"></el-table-column>
            <el-table-column label="创建时间" prop="createTime" align="center" width="120"></el-table-column>
            <el-table-column label="更新时间" prop="updateTime" align="center" width="120"></el-table-column>
            <el-table-column label="操作" align="center">
                <template v-slot="scope">
                    <el-button @click="editDialog(scope.row)" type="text"><el-icon>
                            <Edit />
                        </el-icon>编辑</el-button>
                    <el-button @click="del(scope.row)" type="text" style="color: red"><el-icon>
                            <Delete />
                        </el-icon>删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="padding-left: calc(100% - 650px); text-align: right;margin-top: 10px">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pageSetting.page_num" :page-sizes="[5, 10, 15, 20]" :page-size="pageSetting.page_size"
                layout="total, sizes, prev, pager, next, jumper" :total="pageSetting.total">
            </el-pagination>
        </div>

        <!-- 弹窗 -->
        <div>
            <el-dialog v-model="dialogVisible" :title="editFormTitle" :visible="dialogVisible" width="70%"
                :before-close="handleBeforeClose">
                <el-form :model="editFormData" :rules="editFormRules" label-position="left" ref="editFormRef">
                    <el-form-item label="选择赛事" prop="contestId">
                        <el-select v-model="editFormData.contestId" placeholder="选择赛事">
                            <el-option v-for="(option, index) in chooseEventList" :key="index" :label="option.name"
                                :value="option.contestId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="editFormData.title" placeholder="请输入标题"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="发布者" prop="nickName">
                        <el-input v-model="editFormData.nickName" disabled :placeholder="editFormData.nickName"></el-input>
                    </el-form-item> -->
                    <el-form-item label="动态内容" style="line-height: 40px;" prop="content">
                        <div style="border: 1px solid #ccc; margin-top: 10px;">
                            <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode"
                                style="border-bottom: 1px solid #ccc" />
                            <Editor :defaultConfig="editorConfig" :mode="mode" v-model="valueHtml"
                                style="height: 400px; overflow-y: hidden" @onCreated="handleCreated"
                                @onChange="handleChange" @onDestroyed="handleDestroyed" @onFocus="handleFocus"
                                @onBlur="handleBlur" @customAlert="customAlert" @customPaste="customPaste" />
                        </div>
                    </el-form-item>
                </el-form>

                <solt name="footer" style="padding-left: 70%;">
                    <el-button @click="handleBeforeClose">取消</el-button>
                    <el-button type="primary" @click="handleConfirm">确认</el-button>
                </solt>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, shallowRef, onBeforeUnmount } from 'vue';
// 接口
import {
    GetContestNewsList,
    GetContestNewsListById,
    AddContestNewsList,
    UpdateContestNewsList,
    DeleteContestNewsList,
    GetContestNewsListByName
} from "@/api/back/contesNews";
import {
    GetContestList
} from "@/api/back/contest";
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { ElMessage, messageConfig, ElMessageBox } from "element-plus";

const toggleSearch = ref(false);
// ----------分页查询----------
const pageSetting = ref({
    page_num: 1,
    page_size: 10,
    total: 0
});
// ----------分页查询----------

// ----------分页功能----------
function handleSizeChange(size) {
    pageSetting.value.page_size = size;
    console.log(pageSetting.value.page_size);
    contestNewsList.value = [];
    loadContestNewsList();
}
function handleCurrentChange(page) {
    pageSetting.value.page_num = page;
    console.log(pageSetting.value.page_num);
    contestNewsList.value = [];
    loadContestNewsList();
}
// ----------分页功能----------

// ----------获取赛事动态数据列表----------
// 存放赛事动态数据
const contestNewsList = ref([]);
// 获取赛事动态数据
async function loadContestNewsList() {
    try {
        const response = await GetContestNewsList(pageSetting.value);
        if (response.data) {
            contestNewsList.value = [];
            contestNewsList.value.push(...response.data.pageList);
            pageSetting.value.page_num = response.data.pageNum;
            pageSetting.value.page_size = response.data.pageSize;
            pageSetting.value.total = response.data.total;
            console.log("获取数据列表成功", contestNewsList.value);
        }
    } catch (error) {
        console.error("获取数据列表失败", error);
    }
}
// ----------获取赛事动态数据列表----------


// ----------搜索功能----------
// 存放搜索的值
const searchVal = ref("");
// 搜索功能
async function searchById() {
    try {
        if (searchVal.value == null || searchVal.value == "") {
            GetContestNewsList(pageSetting.value);
        } else {
            const v = {
                search: searchVal.value,
                page: pageSetting.value
            };
            contestNewsList.value = [];
            const response = await GetContestNewsListById(v);
            contestNewsList.value.push(...response.data);
            console.log("搜索成功", response);
        }
    } catch (error) {
        console.log("搜索错误", error);
    }
}
const searchByName = async () => {
    if (searchVal.value == null || searchVal.value == "") {
        ElMessage({
            message: "请输入搜索内容",
            type: "warning"
        });
        return
    }
    contestNewsList.value = [];
    const res = await GetContestNewsListByName({ search: searchVal.value });
    if(res.data.length == 0){
        ElMessage({
          message: "未找到相关动态",
          type: "error",
        });
      }else{
        contestNewsList.value.push(...res.data);
      }
}
// ----------搜索功能----------

// ----------删除功能----------
async function del(row) {
    const id = row.contestNewsId; // 假设ID字段在scope.row中叫做'id'
    ElMessageBox.confirm(
        `将删除动态，是否继续？`,
        '注意',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            try {
                // 需要修改接口
                await DeleteContestNewsList(id); // 向后端传递ID进行删除操作
                // 初始化表单
                contestNewsList.value = [];
                await loadContestNewsList();
                ElMessage({
                    message: "删除成功",
                    type: "success",
                    ...messageConfig,
                });
                console.log("删除成功");
            } catch (error) {
                console.error("删除失败", error);
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消',
            })
        })
}
// ----------删除功能----------


// ----------弹窗选项----------
// 存放赛事列表数据
const contestList = ref([]);
// 获取赛事列表，作用：窗格里的选择赛事实现显示赛事列表名称
async function getContestList() {
    try {
        const response = await GetContestList(pageSetting.value);
        if (response.data) {
            contestList.value.push(...response.data.pageList);
            console.log("获取赛事列表成功", contestList.value);
        }
    } catch (error) {
        console.error("获取赛事列表失败", error);
    }
}
// 选择赛事，显示赛事列表名称
const chooseEventList = ref([]);
async function chooseEvent() {
    try {
        for (let i = 0; i < contestList.value.length; i++) {
            const response = {
                contestId: contestList.value[i].contestId,
                name: contestList.value[i].name
            }
            chooseEventList.value.push(response)
        }
        // console.log("", chooseEventList.value)
    } catch (error) {
        console.log("错误")
    }
}

// 用户名称选项
const publisherOption = JSON.parse(localStorage.getItem('userInfo')).userData[0];
// ----------弹窗选项----------

// ----------弹窗功能----------
// 控制弹窗是否显示
const dialogVisible = ref(false);
const edit = ref(false);
const add = ref(false);
// 弹窗标题
const editFormTitle = ref("");

// 弹窗的数据变量
const editFormData = ref({
    contestNewsId: "",
    contestId: "",
    title: "",
    content: "",
    nickName: publisherOption.nickName,
    publisher: publisherOption.userId,
});

// 控制添加弹窗
const createContest = () => {
    console.log("新增", editFormData.value)
    chooseEvent();
    editFormTitle.value = "创建动态";
    valueHtml.value = "";
    dialogVisible.value = true;
    add.value = true;
};

// 控制编辑弹窗
const editDialog = (rowData) => {
    editFormTitle.value = "编辑动态",
        chooseEvent();
    editFormData.value = {
        contestNewsId: rowData.contestNewsId,
        contestId: rowData.contestId,
        title: rowData.title,
        content: rowData.content,
        nickName: rowData.nickName,
        publisher: rowData.publisher,
    }
    if (rowData.publisher == editFormData.value.publisher) { editFormData.value.publisher = editFormData.value.nickName }
    valueHtml.value = editFormData.value.content;
    dialogVisible.value = true;
    edit.value = true;
};

// 处理添加或编辑弹窗的”确认“按钮
async function handleConfirm() {
    try {
        if (edit.value) {
            if (editFormData.value.publisher == editFormData.value.publisher) { editFormData.value.publisher = publisherOption.userId }
            console.log("编辑成功", editFormData.value);
            await UpdateContestNewsList(editFormData.value);
            edit.value = false;
            chooseEventList.value = [];
        }
        else if (add.value) {
            console.log("添加成功", editFormData.value);
            await AddContestNewsList(editFormData.value);
            add.value = false;
            chooseEventList.value = [];
        }
    } catch (error) {
        console.error("失败", error);
    }
    dialogVisible.value = false;
    contestNewsList.value = [];
    await loadContestNewsList();
}

// 处理窗格的“取消”按钮
function handleBeforeClose() {
    editFormData.value = {
        contestNewsId: "",
        contestId: "",
        title: "",
        content: "",
        nickName: publisherOption.nickName,
        publisher: publisherOption.userId,
    },
        chooseEventList.value = [];
    dialogVisible.value = false;
    edit.value = false;
    add.value = false;
    dialogVisible.value = false;
    console.log("取消")
}
// ----------弹窗功能----------

// ----------富文本编辑器----------
// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref('');

const toolbarConfig = {};
const editorConfig = { placeholder: '请输入内容...' };

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;

    editor.destroy();
});

// 编辑器回调函数
const handleCreated = (editor) => {
    // console.log('created', editor);
    editorRef.value = editor; // 记录 editor 实例，重要！
};
const handleChange = (editor) => {
    editFormData.value.content = editor.getHtml();
    console.log(editFormData.value.content)
};
const handleDestroyed = (editor) => {
    console.log('destroyed', editor);
};
const handleFocus = (editor) => {
    console.log('focus', editor);
};
const handleBlur = (editor) => {
    console.log('blur', editor);
};
const customAlert = (info, type) => {
    alert(`【自定义提示】${type} - ${info}`);
};
const customPaste = (editor, event, callback) => {
    console.log('ClipboardEvent 粘贴事件对象', event);
    // 返回值（注意，vue 事件的返回值，不能用 return）
    callback(true); // 返回 false ，阻止默认粘贴行为
    // callback(true) // 返回 true ，继续默认的粘贴行为
};
// ----------富文本编辑器----------

onMounted(() => {
    loadContestNewsList();
    getContestList();
});
</script>
